<template>
  <div style="height:100%;width:100%">
    <div class="role-tree" v-if="!no_data">
        <div class="search-input">
            <el-input v-model="role_name" :prefix-icon="Search" placeholder="搜索角色"></el-input>
        </div>
        <div class="tree-wrap">
            <el-tree ref="treeRef"
                     :data="data" 
                     :props="defaultProps"
                     :icon="ArrowRight"
                     :filter-node-method="filterNode"
                     empty-text="未找到角色"
                     @node-click="handleNodeClick">
                    <template #default="{node, data}">
                        <span class="customer-tree-node" :class="{disabled:data.enabled === 0}">
                            <gzg-icon name="user"  :color="data.enabled === 0 ? '#C0C4CC' : '#303133'"></gzg-icon>
                            <span class="text">{{node.label}}</span>
                            <span class="tag" v-if="data.enabled === 0">未启用</span>
                            <el-dropdown trigger="contextmenu" @command="handleCommand($event,data,node)">
                                <span class="el-dropdown-link">
                                    <gzg-icon name="more-vertical" :color="data.enabled === 0 ? '#C0C4CC' : '#303133'"></gzg-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item command="edit">编辑名称</el-dropdown-item>
                                        <el-dropdown-item command="add">新增下级角色</el-dropdown-item>
                                        <el-dropdown-item command="disable">{{data.enabled == 1 ? '禁用' : '启用'}}</el-dropdown-item>
                                        <el-dropdown-item command="delete" style="color:#F56C6C">删除</el-dropdown-item>

                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </span>
                    </template>
            </el-tree>
        </div>
        <div class="btn-wrap">
            <el-button type="primary" :icon="Plus" @click="add(undefined)">新建角色</el-button>
        </div>
    </div>
    <div class="no-data-wrap" v-else>
       <el-empty description="你还没有创建角色">
            <el-button type="primary" @click="add(undefined)" >创建角色</el-button>
        </el-empty>
    </div>
    <el-dialog title="新建角色" v-model="visible" width="480px" :close-on-click-modal="false">
      <el-form ref="formRef"
               :model="form"
                 :rules="formRules"
                 :label-width="120">
        <el-form-item label="角色名称:" prop="role_name">
          <el-input v-model="form.role_name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="上级角色:" prop="parent_id" v-if="Boolean(form.parent_id)">
          <el-tree-select v-model="form.parent_id" 
                          disabled
                          style="width:100%"
                          check-strictly
                          :data="data" 
                          :render-after-expand="false"
                          :props="{
                            label:'role_name',
                            value:'id'
                          }"></el-tree-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
                <el-switch v-model="form.enabled"
                           :active-value="1"
                           :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="save(formRef)">确 定</el-button>
        </div>
      </template>
      
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { Search, ArrowRight, Plus } from '@element-plus/icons-vue'
import { ElTree, ElMessageBox, ElMessage } from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'

import { getRoleList, saveRole, toggleRole, deleteRole } from 'services/setting'

import type Node from 'element-plus/es/components/tree/src/model/node'

interface Tree {
    id?: number,
    role_name:string,
    role_sort?: number,
    parent_id?: number | undefined,
    enabled: number,
    can_delete?: number,
    children?: Tree[]
}

const emits = defineEmits(['selectNode'])

const formRef = ref<FormInstance>()

const formRules = reactive<FormRules>({
  role_name:[{required:true, message:'请输入角色名称', trigger:'blur'}]
})

const form = ref<Tree>({
    role_name:'',
    enabled: 1,
    parent_id: undefined,
})

const role_name = ref('')
const no_data = ref(false)
const treeRef = ref<InstanceType<typeof ElTree>>()
const visible = ref(false)
const data = ref<Tree[]>([])

const handleNodeClick = (data:Tree) => {
    console.log(data)
    emits('selectNode', data.id)
}

const handleCommand = (command:string,data:Tree,node:Node) => {
    switch (command) {
      case 'add':
        add(data.id)
        break;
      case 'edit':
        edit(data)
        break;
      case 'disable':
        handleEnable(data)
        break
      case 'delete':
        handleDelete(data)
        break
      default:
        break;
    }
}

const filterNode = (value:string, data:Tree) => {
    if (!value) return true
    return data.role_name.includes(value)
}

watch(role_name, (val) => {
    treeRef.value!.filter(val)
})


const getRoleData = () => {
  getRoleList().then((res:any) => {
    console.log(res)
    if (res.length == 0) {
      no_data.value = true
    } else {
      no_data.value = false
      data.value = res;
    }
  })
}

const defaultProps = {
    children:'children',
    label:'role_name'
}

const add = (parent_id: number | undefined) => {
  form.value.parent_id = parent_id 
  visible.value = true;
  formRef.value?.resetFields()
}

const edit = (detail:Tree) => {
  form.value = {
    id:detail.id,
    parent_id: detail.parent_id,
    role_name: detail.role_name,
    enabled: detail.enabled
  }

  visible.value = true;
}

const handleEnable = (row:Tree) => {
  let enabled = row.enabled;
  ElMessageBox.confirm(`确认进行【${enabled === 1 ? '禁用' : '启用'}】操作`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        toggleRole({
            id:row.id || undefined,
            enabled: enabled === 1 ? false : true
        }).then(res => {
            getRoleData()
            ElMessage.success('操作成功')
        })
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const handleDelete = (row:Tree) => {
  ElMessageBox.confirm('确认进行【删除】操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then((result) => {
        deleteRole({id:row.id || undefined}).then(res => {
            getRoleData()
            ElMessage.success('删除成功')
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            saveRole(form.value).then(res => {
                ElMessage.success('操作成功')
                visible.value = false
                getRoleData()
            })
        } else {
            console.log('error submit', fields)
        }
    }) 
}

onMounted(() => {
  getRoleData()
})

</script>
<style lang="scss">
.role-tree{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .search-input{
        height: 32px;
        margin-bottom: 16px;
    }

    .tree-wrap{
        flex: 1;
        height: 0;
        width: 100%;
        overflow-y: scroll;
    }

    .btn-wrap{
        margin-top: 16px;

        .el-button{
            width: 100%;
        }
    }

    .el-tree{
        .el-tree-node__content{
            height: 48px;

            &:hover{
              background-color: #ECF5FF;

              .customer-tree-node{
                color: #2770EE;
              }
              
              .gzg-icon{
                color: #2770EE !important;
              }
            }
        }

        .customer-tree-node{
            width: 100%;
            display: flex;
            box-sizing: border-box;
            padding-right: 10px;
            color: #303133;

            .text{
              margin-left: 10px;
              margin-right: auto;

            }

            .tag{
              margin-right: 4px;
            }

            &.disabled{
              color: #C0C4CC;
            }

            .el-dropdown-link{
              display: flex;
              align-items: center;
            }
        }
    }
}
</style>